package com.heima.test5;

import java.util.concurrent.locks.ReentrantLock;

public class SellTicket implements Runnable {
    private int tickets = 100;
    ReentrantLock lock = new ReentrantLock();

    //在SellTicket类中重写run()方法实现卖票，代码步骤如下
    @Override
    public void run() {
        while (true) {
            lock.lock();//上锁
            if (tickets <= 0) {
                //判断ticket数量小于等于0，说明卖完了，结束循环
                break;
            } else {
                try {
                    Thread.sleep(100);//模拟卖票消耗100ms
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                tickets--;//卖票 导致数量-1
                System.out.println(Thread.currentThread().getName() + "在卖票,还剩下" + tickets + "张票");
            }
            lock.unlock();
        }
    }
}